<script>
export default {
  data() {
    return {
      classinfos: [],
      classinfo: {
        classId: '',
        className: ''
      },
      classinfoFormVisible: false,
      tableHeight: window.innerHeight - 220,
      // 分页属性
      total: 0,
      pageSize: 10,
      current: 1,
      operate: '',
      // 表单验证
      rules: {
        classId: [
          {required: true, message: '班级ID', trigger: 'change'}
        ],
        className: [
          {required: true, message: '班级名称', trigger: 'change'}
        ]
      },
      // 搜索关键字变量
      searchKeyword: ''
    }
  },
  methods: {
    operateClass(classinfo) {
      this.$http.post("/class/" + this.operate, classinfo).then((response) => {
        if (response.status === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.loadClasses(this.current);
          this.classinfoFormVisible = false;
        } else {
          this.$message({
            type: 'error',
            message: response.data
          });
        }
      });
    },
    handleClose() {
      this.classinfo.classId = '';
      this.classinfo.className = '';
      this.loadClasses(this.current);
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该班级信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.operate = 'delete';
        this.operateClass(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleEdit(index, row) {
      this.operate = 'modify';
      this.classinfo = JSON.parse(JSON.stringify(row));
      this.classinfoFormVisible = true;
    },
    addFrom() {
      this.operate = 'add';
      this.classinfo = {
        classId: '',
        className: ''
      };
      this.classinfoFormVisible = true;
    },
    calculateTableHeight() {
      // 动态计算表格高度，
      this.tableHeight = window.innerHeight - 220;
    },
    loadClasses() {
      this.$http.get(`/class/${this.current}/${this.pageSize}`)
          .then(res => {
            console.log(res.data);
            if (res.data) {
              this.classinfos = res.data.records;
              this.total = res.data.total;
              if (this.classinfos.length === 0 && this.current > 1) {
                this.current -= 1;
                this.loadClasses(this.current);
              }
            }
          })
    },
    // 搜索
    handleSearch() {
      if (this.searchKeyword.trim() === '') {
        // 如果搜索关键字为空，可以考虑重置为默认数据
        this.loadClasses(this.current);
      } else {
        this.$http.get(`/class/search?keyword=${encodeURIComponent(this.searchKeyword)}`)
            .then(res => {
              if (res.data) {
                this.classinfos = res.data;
                // 打印日志确认数据是否正确
                console.log("返回查询数据:" + this.classinfos);
              } else {
                console.error('无效的响应数据：', res.data);
              }
            })
            .catch(error => {
              console.error('错误搜索:', error);
            });
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      console.log("分页大小：" + this.pageSize + "、当前页" + this.current);
      this.loadClasses(this.current);
    }
    ,
    handleCurrentChange(val) {
      this.current = val;
      console.log("分页大小：" + this.pageSize + "、当前页" + this.current);
      this.loadClasses(this.current);
    }
    ,
  },
  mounted() {
    this.loadClasses();
    // 窗口大小变化事件的监听器
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeDestroy() {
    // 组件销毁前移除窗口大小变化事件的监听器
    window.removeEventListener('resize', this.calculateTableHeight);
  }
}
</script>

<template>
  <div style="height: 100%">
    <div style="position: relative;">
      <h1 style="position: absolute;margin-top: 0">班级信息管理</h1>
      <div style="text-align: left;">
        <el-input v-model="searchKeyword" placeholder="全局搜索" style="width: 200px; margin-right: 10px;"></el-input>
        <el-button round type="primary" @click="handleSearch">搜索</el-button>
        <el-button class="add-button" round type="primary" @click="addFrom()">添加班级信息</el-button>
      </div>
    </div>
    <el-dialog :visible.sync="classinfoFormVisible" title="班级信息" @close="handleClose">
      <el-form ref="classinfoForm" :model="classinfo" :rules="rules" label-width="auto">
        <!--        <el-form-item label="班级 ID" prop="classId">-->
        <!--          <el-input v-model.trim="classinfo.classId" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="班级名称" prop="className">
          <el-input v-model.trim="classinfo.className" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="classinfoFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="operateClass(classinfo)">确 定</el-button>
      </div>
    </el-dialog>
    <el-table
        :data="classinfos"
        :height="tableHeight"
        border style="width: 100%;">
      <el-table-column
          fixed
          label="ID"
          min-width="100px"
          prop="classId">
      </el-table-column>
      <el-table-column
          label="班级名称"
          min-width="100px"
          prop="className">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="150px">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          :current-page="current"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          :total="total"
          background
          class="custom-pagination"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>




